﻿/*
 * FileName:    VelocityMultiPathConfigurer.java
 * Description:
 * Company:     南宁超创信息工程有限公司
 * Copyright:   ChaoChuang (c) 2005
 * History:     2005-5-23 (guig) 1.0 Create
 */
package com.wky.common.util;

import java.io.File;
import java.io.IOException;

import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.servlet.view.velocity.VelocityConfigurer;

/**
 * @author guig
 * @version 1.0 2005-5-23
 */
public class VelocityMultiPathConfigurer extends VelocityConfigurer {

    private ResourceLoader resourceLoader = null;
    private String resourceLoaderPath = null;

    /**
     * @see org.springframework.ui.velocity.VelocityEngineFactory#setResourceLoaderPath(java.lang.String)
     */
    public void setResourceLoaderPath(String resourceLoaderPath) {
        this.resourceLoaderPath = resourceLoaderPath;
        super.setResourceLoaderPath(resourceLoaderPath);
    }

    /**
     * @see org.springframework.ui.velocity.VelocityEngineFactory#setResourceLoader(org.springframework.core.io.ResourceLoader)
     */
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
        super.setResourceLoader(resourceLoader);
    }

    /**
     * @see org.springframework.ui.velocity.VelocityEngineFactory#postProcessVelocityEngine(org.apache.velocity.app.VelocityEngine)
     */
    protected void postProcessVelocityEngine(VelocityEngine velocityEngine) {

        if ((null != this.resourceLoader) && (null != this.resourceLoaderPath) ) {
            String[] paths = this.resourceLoaderPath.split(",");
            StringBuffer filePaths = new StringBuffer();
            try {
                for (int i = 0; i < paths.length; i++) {
                    if (filePaths.length() > 0) {
                        filePaths.append(", ");
                    }
                    Resource path = this.resourceLoader.getResource(paths[i]);
                    File file = path.getFile();  // will fail if not resolvable in the file system

                    filePaths.append(file.getAbsolutePath());
                }
                velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "file");
                velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, filePaths.toString());
                velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, "true");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        super.postProcessVelocityEngine(velocityEngine);
    }

}

